// TCP服务器
#include <iostream>
#include <vector>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include "tcp_server.h"

const int PORT = 8001;

int startTcpServer(SampleProcess& process, void* inputBuffer) {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    // float buffer[16];
    float *buffer = reinterpret_cast<float*>(inputBuffer);

    // 创建socket文件描述符
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 绑定socket到指定端口
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    std::size_t recvCnt = 0;
    int FRAME_SIZE = 16*2*10000*4;
    float *recvBuffer = new float[FRAME_SIZE*2];
    while (true) {
        std::cout << "Waiting for new connection..." << std::endl;
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
            perror("accept");
            exit(EXIT_FAILURE);
        }
        int num = 0;
        while (true) {
            // 接收16个浮点数
            std::size_t bytes_received = read(new_socket, &recvBuffer[recvCnt], FRAME_SIZE);
            recvCnt += bytes_received;
            if (recvCnt < FRAME_SIZE) { // 还没收到一帧数据，继续接收
                continue;
            }
            std::cout << "???????????????????? cnt=" << bytes_received << "; recvCnt=" << recvCnt << ";" << std::endl;
            // 打印接收到的浮点数
            // std::cout << "Received floats: ";
            // for (int i = 0; i < 320000; ++i) { // 共有16帧复数长度为10000=16*2*10000
            //     std::cout << buffer[i] << " ";
            // }
            // std::cout << std::endl;
            if (recvCnt >= FRAME_SIZE) {
                memcpy(buffer, recvBuffer, FRAME_SIZE);
                process.Infer(inputBuffer); // 执行推理引擎
                recvCnt -= FRAME_SIZE; // 这里是下一帧中刚接收到的数据
                memcpy(&recvBuffer[0], &recvBuffer[FRAME_SIZE], recvCnt);
            }
            std::cout << "##################### send back ####################" << std::endl;
        }
        
        // 关闭socket连接
        close(new_socket);
    }

    // 关闭服务器socket
    shutdown(server_fd, SHUT_RDWR);
    return 0;
}
